<template>
  <div class="graphs-menu">
    <div class="graphs-menu-title">矢量库</div>
    <div class="graphs-menu-items">
      <div
        class="graphs-menu-item"
        v-for="(subItem, subIndex) in menuItems"
        :key="subIndex"
        @click="handleItemClick(subItem)"
      >
        <div class="menu-item-icon">
          <IconFont class="icon" :name="subItem.icon" size="2.0833vw" />
          <!-- <img :src="subItem.icon" alt="功能图标" /> -->
        </div>
        <div class="menu-item-text">{{ subItem.text }}</div>
      </div>
    </div>

    <div class="graphs-menu-button">
      <button class="menu-button" @click="clear">撤销</button>
      <button class="menu-button" @click="clearAll">清除全部</button>
    </div>
  </div>
</template>
<script setup>
/**
 * [MODIFIED] Changed component description
 * 左侧垂直工具栏组件
 *
 * 功能：显示绘图工具和操作按钮，如折线、圆形、矩形、多边形、撤销和清除全部
 */
import { ref, onMounted, onUnmounted } from 'vue'
import { useBottomBarStore } from '@/stores/bottomBarStore.js'
import { getobjm } from '@/utils/getobjm.js'
import { ESGeoLineString, ESLocalCircle, ESGeoRectangle, ESGeoPolygon } from 'earthsdk3'
import { useTreeStore } from '@/stores/treeStore.js'
const treeStore = useTreeStore()
// 初始化状态管理和工具
const bottomBarStore = useBottomBarStore()
const objm = getobjm()

// 当前选中的导航项索引
const selectedItem = ref(null)
// [MODIFIED] Renamed ref
const sidebarRef = ref(null)
/**
 * [MODIFIED] Renamed configuration
 * 侧边栏菜单项配置
 * @type {Array<Object>} 菜单项数组
 * @property {string} text - 菜单项显示文本
 * @property {string} icon - 菜单项图标
 * @property {string} type - 菜单项类型，用于确定执行的操作
 */
const menuItems = ref([
  {
    text: '折线',
    icon: 'zx',
    type: 'line',
  },
  {
    text: '圆',
    icon: 'yuan',
    type: 'circle',
  },
  {
    text: '矩形',
    icon: 'jx',
    type: 'rectangle',
  },
  {
    text: '多边形',
    icon: 'dbx',
    type: 'polygon',
  },
  // {
  //   text: '撤回',
  //   icon: 'ch',
  //   type: 'clear',
  // },
  // {
  //   text: '清空',
  //   icon: 'qk',
  //   type: 'clearAll',
  // },
])

/**
 * 处理导航项点击事件
 * @param {Object} item - 点击的菜单项
 * @param {number} index - 菜单项的索引
 */
const handleItemClick = (item, index) => {
  // 执行相应的操作
  createVector(item)

  // 对于撤销和清除全部功能，不设置选中状态
  if (item.type === 'clear' || item.type === 'clearAll') {
    if (selectedItem.value !== null) {
      selectedItem.value = null
    }
    return
  }
  // 对于其他功能，设置当前选中的项
  selectedItem.value = index
}

/**
 * 根据菜单项类型创建相应的矢量对象
 * @param {Object} item - 菜单项对象
 */
const createVector = (item) => {
  switch (item.type) {
    case 'line':
      createESGeoLineString()
      break
    case 'circle':
      createESLocalCircle()
      break
    case 'rectangle':
      createESGeoRectangle()
      break
    case 'polygon':
      createESGeoPolygon()
      break
    case 'clear':
      clear()
      break
    case 'clearAll':
      clearAll()
      break
    default:
      console.log(`未知功能: ${item.type}`)
  }
}
// 定义emit，用于通知父组件关闭子菜单
const emit = defineEmits(['close-submenu'])
// --- 绘图和清除逻辑 (无变化) ---
const createESGeoLineString = () => {
  const sceneObjectESGeoLineString = objm.createSceneObject(ESGeoLineString)
  if (!sceneObjectESGeoLineString) return
  sceneObjectESGeoLineString.stroked = true
  sceneObjectESGeoLineString.strokeWidth = 5
  sceneObjectESGeoLineString.editing = true
  sceneObjectESGeoLineString.editingChanged.disposableWeakOn(() => {
    if (sceneObjectESGeoLineString && sceneObjectESGeoLineString.editing === false) {
      const pos = sceneObjectESGeoLineString.points?.length
      const json = sceneObjectESGeoLineString.json
      objm.destroySceneObject(sceneObjectESGeoLineString)
      setTimeout(() => {
        if (pos && pos >= 2) {
          const addTree = treeStore.createSceneObjectTreeItemFromJson(json)
          bottomBarStore.createBottomBarData.push(addTree)
          if (addTree) treeStore.treeChange()
        }
      }, 300)
    }
  })
  emit('close-submenu')
}

const createESLocalCircle = () => {
  const sceneObjectESLocalCircle = objm.createSceneObject(ESLocalCircle)
  if (!sceneObjectESLocalCircle) return
  sceneObjectESLocalCircle.editing = true
  sceneObjectESLocalCircle.editingChanged.disposableWeakOn(() => {
    if (sceneObjectESLocalCircle && sceneObjectESLocalCircle.editing === false) {
      const position = sceneObjectESLocalCircle.position
      const a = position[0] === 0 && position[1] === 0
      const json = sceneObjectESLocalCircle.json
      objm.destroySceneObject(sceneObjectESLocalCircle)
      setTimeout(() => {
        if (!a) {
          const addTree = treeStore.createSceneObjectTreeItemFromJson(json)
          bottomBarStore.createBottomBarData.push(addTree)
          if (addTree) treeStore.treeChange()
        }
      }, 300)
    }
  })
  emit('close-submenu')
}

const createESGeoRectangle = () => {
  const sceneObjectESGeoRectangle = objm.createSceneObject(ESGeoRectangle)
  if (!sceneObjectESGeoRectangle) return
  sceneObjectESGeoRectangle.editing = true
  sceneObjectESGeoRectangle.editingChanged.disposableWeakOn(() => {
    if (sceneObjectESGeoRectangle && sceneObjectESGeoRectangle.editing === false) {
      const pos = sceneObjectESGeoRectangle.points?.length
      const json = sceneObjectESGeoRectangle.json
      objm.destroySceneObject(sceneObjectESGeoRectangle)
      setTimeout(() => {
        if (pos && pos >= 2) {
          const addTree = treeStore.createSceneObjectTreeItemFromJson(json)
          bottomBarStore.createBottomBarData.push(addTree)
          if (addTree) treeStore.treeChange()
        }
      }, 300)
    }
  })
  emit('close-submenu')
}

const createESGeoPolygon = () => {
  const sceneObjectESGeoPolygon = objm.createSceneObject(ESGeoPolygon)
  sceneObjectESGeoPolygon.editing = true
  sceneObjectESGeoPolygon.editingChanged.disposableWeakOn(() => {
    if (sceneObjectESGeoPolygon && sceneObjectESGeoPolygon.editing === false) {
      const pos = sceneObjectESGeoPolygon.points?.length
      const json = sceneObjectESGeoPolygon.json
      objm.destroySceneObject(sceneObjectESGeoPolygon)
      setTimeout(() => {
        if (pos && pos >= 3) {
          const addTree = treeStore.createSceneObjectTreeItemFromJson(json)
          bottomBarStore.createBottomBarData.push(addTree)
          if (addTree) treeStore.treeChange()
        }
      }, 300)
    }
  })
  emit('close-submenu')
}

const clear = () => {
  if (bottomBarStore.hasCreateBottomBarData) {
    const recently = bottomBarStore.createBottomBarData.pop()
    treeStore.destroySceneObjectTreeItem(recently)
    treeStore.treeChange()
  }
}

const clearAll = () => {
  if (!bottomBarStore.hasCreateBottomBarData) return
  bottomBarStore.createBottomBarData.forEach((item) => {
    if (item) treeStore.destroySceneObjectTreeItem(item)
  })
  treeStore.treeChange()
  bottomBarStore.createBottomBarData = []
}

/**
 * 处理全局点击事件
 * @param {Event} event - 点击事件对象
 */
const handleClickOutside = (event) => {
  if (selectedItem.value === null) return
  // [MODIFIED] Use the renamed ref
  const isClickInSidebar = sidebarRef.value && sidebarRef.value.contains(event.target)
  if (!isClickInSidebar) {
    selectedItem.value = null
  }
}

// 挂载和卸载事件监听器
onMounted(() => {
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})
</script>

<style lang="scss" scoped>
.graphs-menu {
  width: 15.625vw /* 300px -> 15.625vw */;
  background-color: rgba(0, 8, 26, 0.8);
  border-radius: 0.4167vw /* 8px -> .4167vw */;
  box-shadow: 0 0 0.5208vw /* 10px -> .5208vw */ rgba(0, 195, 255, 0.5);
  border: 0.0521vw /* 1px -> .0521vw */ solid rgba(0, 195, 255, 0.6);
  padding: 0.5208vw /* 10px -> .5208vw */;
  z-index: 2;
  .graphs-menu-title {
    font-size: 0.8333vw /* 16px -> .8333vw */;
    color: #00c3ff;
    font-weight: bold;
    padding-bottom: 0.5208vw /* 10px -> .5208vw */;
    border-bottom: 0.0521vw /* 1px -> .0521vw */ solid rgba(0, 195, 255, 0.3);
  }

  .graphs-menu-items {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    gap: 0.7813vw /* 15px -> .7813vw */;
    padding: 0.5208vw /* 10px -> .5208vw */ 0;
    flex-wrap: wrap;
    max-height: 10.4167vw /* 200px -> 10.4167vw */;
    overflow: auto;
    // 自定义滚动条样式
    &::-webkit-scrollbar {
      width: 0.4167vw /* 8px -> .4167vw */; // 滚动条宽度
    }

    &::-webkit-scrollbar-track {
      background: rgba(0, 0, 0, 0.3); // 滚动条轨道背景
      border-radius: 0.2083vw /* 4px -> .2083vw */; // 轨道圆角
    }

    &::-webkit-scrollbar-thumb {
      background: rgba(0, 195, 255, 0.5); // 滚动条滑块颜色
      border-radius: 0.2083vw /* 4px -> .2083vw */; // 滑块圆角
    }
    .graphs-menu-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      gap: 0.5208vw /* 10px -> .5208vw */;
      width: 4.1667vw /* 80px -> 4.1667vw */;
      height: 4.1667vw /* 80px -> 4.1667vw */;
      cursor: pointer;
      border-radius: 0.2083vw /* 4px -> .2083vw */;

      &:hover {
        background-color: rgba(0, 195, 255, 0.2);
        .menu-item-icon {
          .icon {
            scale: 0.9;
          }
        }
      }

      &.active {
        background-color: rgba(0, 195, 255, 0.3);
        border: 0.0521vw /* 1px -> .0521vw */ solid rgba(0, 195, 255, 0.8);

        .menu-item-text {
          color: #00c3ff;
          font-weight: bold;
        }
      }

      .menu-item-icon {
        .icon {
          width: 2.0833vw /* 40px -> 2.0833vw */;
          height: 2.0833vw /* 40px -> 2.0833vw */;
          object-fit: contain;
          transition: all 0.5s;
        }
      }
      .menu-item-text {
        height: 0.8333vw /* 16px -> .8333vw */;
        line-height: 0.8333vw /* 16px -> .8333vw */;
        font-size: 0.625vw /* 12px -> .625vw */;
        color: #ffffff;
        text-align: center;
      }
    }
  }
  .graphs-menu-button {
    padding-top: 0.5208vw /* 10px -> .5208vw */;
    border-top: 0.0521vw /* 1px -> .0521vw */ solid rgba(0, 195, 255, 0.3);
    display: flex;
    justify-content: space-between;
    align-items: center;
    .menu-button {
      background-color: rgba(0, 195, 255, 0.2);
      border: 0.0521vw /* 1px -> .0521vw */ solid rgba(0, 195, 255, 0.6);
      color: #00c3ff;
      padding: 0.2604vw /* 5px -> .2604vw */ 0.4167vw /* 8px -> .4167vw */;
      border-radius: 0.2083vw /* 4px -> .2083vw */;
      font-size: 12px;
      cursor: pointer;
      &:hover {
        background-color: rgba(0, 195, 255, 0.4);
      }
    }
  }
}
</style>
